package com.favorites.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import com.favorites.vo.RequestWithCookie;
import com.favorites.vo.TouTiao;
import com.favorites.vo.TouTiaoBlog;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by
 *
 * @author dw
 * @date 2018/04/02
 */
public class ParseBase {
    private static final Logger logger = LoggerFactory.getLogger(ParseBase.class);
    private static final String SPLITSTR = "~~~";

    public static String FAVORITESURLS = "favorites_urls";

    public static void main(String[] args) {
    }

    public final Map<String, RequestWithCookie> getFavoritesSetting() {
        Map<String, RequestWithCookie> re = new HashMap<String, RequestWithCookie>();
        Setting setting = new Setting("favorites.setting");
        System.out.println(setting.getSettingPath());
        String toutiao_cookies = setting.getStr("toutiao_cookies");

        Map<String, String> favorites_urls = (Map<String, String>) setting.getMap(FAVORITESURLS);
        System.out.println(favorites_urls.size());
        favorites_urls.forEach((key, value) -> {
            logger.debug("url: " + value);
            RequestWithCookie recookie = null;
            if (StrUtil.isNotBlank(value)) {
                recookie = new RequestWithCookie();
                //getUrlAndCookies(recookie, value);
                recookie.setCookies(toutiao_cookies);
                recookie.setUrl(value);
                re.put(key, recookie);
            }
        });
        return re.size() > 0 ? re : null;

    }

    @Deprecated
    private void getUrlAndCookies(RequestWithCookie recookie, String value) {
        try {
            String[] re = value.split(SPLITSTR);
            recookie.setUrl(re[0]);
            recookie.setCookies(re[1]);
        } catch (Exception e) {
            logger.error("定义链接地址和cookies方式异常(url和cookies直接用" + SPLITSTR + "):" + value, e);
        }
    }

    public final void makeSingsFile(String filePath) {
        File temp = new File(filePath);

        OutputStreamWriter opsw = null;
        BufferedWriter bw = null;

        try {
            if (!temp.exists()) {
                temp.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(temp);
            opsw = new OutputStreamWriter(fileOutputStream);
            bw = new BufferedWriter(opsw);

            bw.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            // 声明资源时要分析好资源关闭顺序,先声明的后关闭
            try {
                bw.close();
                opsw.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }

    }

    public final List<TouTiaoBlog> getDataFromToutiao(RequestWithCookie value, String beforYear) {
        logger.debug("parseJson...");
        String next = "0";
        List<TouTiaoBlog> datas = new ArrayList();
        List<TouTiaoBlog> datasUse = new ArrayList();
        while (null != next) {
            try {
                logger.debug("下一页访问标记：" + next);
                String url = null;
                if ("".equals(url)) {
                    url = value.getUrl();
                } else {
                    url = value.getUrl() + "?max_repin_time=" + next;
                }
                logger.debug("采集页面:" + url);
                HttpRequest httpRequest = HttpUtil.createGet(url);
                httpRequest.cookie(value.getCookies());
                httpRequest.timeout(Integer.MAX_VALUE);
                httpRequest.contentType("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
                httpRequest.contentType("application/x-www-form-urlencoded");

                java.lang.String alljson = httpRequest.execute().body();
                logger.debug(alljson);
                TouTiao o = JSONUtil.toBean(alljson, TouTiao.class);
                int[] i = {1};
                if (null != o && "success".equals(o.getMessage())) {
                    o.getData().forEach(datev -> {
                        logger.debug("序号" + i[0] + "  标题:{} 发布时间{}  访问链接:{}", datev.getTitle(), datev.getBehot_time(), datev.getDisplay_url());
                        i[0]++;
                    });
                }
                //通过next停止循环
                next = StrUtil.isBlank(o.getMax_repin_time()) ? null : o.getMax_repin_time();
                if (null != next) {
                    String repin_time = o.getData().get(o.getData().size() - 1).getRepin_time();
                    if (repin_time.contains(beforYear)) {
                        next = null;
                    }
                }
                datas.addAll(o.getData());
                //通过next停止循环
                Thread.sleep(RandomUtil.randomSleep());
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
        datasUse = datas.stream().filter((TouTiaoBlog c) -> !c.getRepin_time().contains(beforYear)).collect(Collectors.toList());
        datasUse.sort((TouTiaoBlog t1, TouTiaoBlog t2) -> t2.getRepin_time().compareTo(t1.getRepin_time()));
        return datasUse;
    }

}
